package com.ubxtech.core.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Victor.Xiao
 * @since 2023-08-24 10:44
 **/
public class GrayVersionUtil {

    /**
     * 比较灰度版本是否匹配,region和zone默认都是all
     * @author Victor.Xiao
     * @since 2023-08-24 11:00
     * @param serverVersion 完整示例应该是region-zone-version
     * @param userVersion userVersion
     * @return boolean
    */
    public static boolean compareGrayVersion(String serverVersion, String userVersion) {
        userVersion = fillVersion(userVersion);
        serverVersion = fillVersion(serverVersion);
        return userVersion.equalsIgnoreCase(serverVersion);
    }
    /**
     * 填充 all
     * version> all-all-version
     * zone1-version> all-zone1-version
     * @author Victor.Xiao
     * @since 2023-08-24 11:14
     * @param version version
     * @return java.lang.String
    */
    public static String fillVersion(String version) {
        if (StrUtil.isBlank(version)) {
            return StrPool.GRAY_ALL;
        }
        String[] versionArr = version.split("-");
        //只有一个返回all-all
        if (versionArr.length == 1) {
            return StrPool.ALL + "-" + StrPool.ALL + "-" + version;
        } else if (versionArr.length == 2) {
            return StrPool.ALL + "-" + version;
        }
        return version;
    }


    public static <T> T getInstance(List<T> instances,String balanceType) {
        return getInstance(instances, balanceType, null);
    }

    public static <T> T getInstance(List<T> instances, String balanceType, AtomicInteger nextServerAtomic) {
        //轮询
        if ("1".equalsIgnoreCase(balanceType) && nextServerAtomic != null) {
            int pos = nextServerAtomic.incrementAndGet() & Integer.MAX_VALUE;
            return instances.get(pos % instances.size());
        }
        //随机
        else if ("2".equalsIgnoreCase(balanceType)) {
            return instances.get(RandomUtil.randomInt(instances.size()));
        }
        return instances.get(RandomUtil.randomInt(instances.size()));
    }

}
